package com.tm.dao.impl;

import com.tm.dao.IStudentDao;
import com.tm.entity.Student;
import com.tm.util.DruidUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class StudentDaoImpl implements IStudentDao{

    private QueryRunner qr = new QueryRunner(DruidUtil.getDataSource());

    @Override
    public List<Student> getAllStudents() {
        try {
            return qr.query("select * from stu", new BeanListHandler<Student>(Student.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Student> getStudentsByPage(int cp, int ps) {
        int si = (cp - 1) * ps;

        try {
            return qr.query("select * from stu limit ?, ?", new BeanListHandler<Student>(Student.class), si, ps);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Student getStudentBySid(int stuId) {
        try {
            return qr.query("select * from stu where stu_id = ?", new BeanHandler<Student>(Student.class), stuId);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int saveStudent(Student stu) {
        try {
            return qr.update("insert into stu(stu_id, stu_name, stu_sex, c_id) values(?, ?, ?, ?)",
                    stu.getStu_id(),stu.getStu_name(), stu.getStu_sex(), stu.getC_id());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int deleteStudent(int stuId) {
        try {
            return qr.update("delete from stu where stu_id = ?", stuId);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int updateStudent(Student stu) {
        try {
            return qr.update("update stu set stu_name = ?, stu_sex = ?, c_id = ? where stu_id = ?",
                    stu.getStu_name(), stu.getStu_sex(), stu.getC_id(), stu.getStu_id());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
